package com.vercon.otamirror.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.vercon.commonmirror.utils.LogUtils;
import com.vercon.otamirror.MainActivity;
import com.vercon.otamirror.event.AppDeleteEvent;
import com.vercon.otamirror.event.InstalledEvent;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by csh on 2021/3/23
 * 监听系统安装应该成功监听，安卓通用
 */
public class InstallBroadcast extends BroadcastReceiver {
    public static boolean isUpdate = true;//标记是否更新本APP

    @Override
    public void onReceive(Context context, Intent intent) {
        LogUtils.i("InstallBroadcast", intent.getAction());

        if (Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())) {
            //有应用被替换
            LogUtils.d("有应用被替换");
            String packageName = intent.getData().getSchemeSpecificPart();

            if (packageName.equals(context.getPackageName())) {
                //自身APP更新
                LogUtils.d("isUpdate true");
                Intent it = new Intent(context, MainActivity.class);
                it.setAction(Intent.ACTION_VIEW);
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(it);
//                Intent intent1 = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
//                if (null != intent1) {
//                    context.startActivity(intent1);
//                }
            } else {
                LogUtils.d("isUpdate false");
            }
        } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
            //有应用被添加，第一次安装，和更新安装都跑
            LogUtils.d("有应用被添加");
           EventBus.getDefault().post(new InstalledEvent(true));
       } else if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
           //卸载APP回调
           EventBus.getDefault().post(new AppDeleteEvent(true));
       } else {
           LogUtils.i("InstallBroadcast", intent.getAction());
       }
    }
}